package com.example.homework.utils;

import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class NetUtil {
    public static final String URL_WEATHER = "https://v1.yiketianqi.com/free/day?appid=93952199&appsecret=36U61WDL&unescape=1";
    public static String doGet(String urlStr) {
        String result = "";
        HttpURLConnection connection = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader bufferedReader = null;
// 连接网络
        try {
            URL url = new URL(urlStr);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(10000);
// 从请求的连接中读取天气数据(二进制)
            InputStream inputStream = connection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
// 将二进制数据流放入缓冲区
            bufferedReader = new BufferedReader(inputStreamReader);
// 从缓冲区读取一行行字符串
            StringBuilder stringBuilder = new StringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
            result = stringBuilder.toString();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }
    public static String getWeatherOfCity(String city) {
        String weatherResult = "";
// 拼接获取天气数据的URL
// public static Ũ nal String URL_WEATHER = "https://www.yiketianqi.com/free/day?

        String weatherUrl = URL_WEATHER + "&city=" + city;
        Log.d("res", "getWeatherOfCity: " + weatherUrl);
        weatherResult = doGet(weatherUrl);
        Log.d("res", "getWeatherOfCity: " + weatherUrl);
        return weatherResult;
    }
}
